package zkclient

import (
	"fmt"
	"github.com/samuel/go-zookeeper/zk"
	"EasyData/global"
	log "code.google.com/p/log4go"
	"EasyData/zkclient/basic"
)

const (
	deleteType  = "EventNodeDeleted"
	createType = "EventNodeCreated"
)
/**
	监听和事件通知
 */
type taskWatcherAndNotify struct {
	channel chan (<-chan zk.Event)
	task *global.Task
	path string
}


/**
	注册任务回调用
 */
func (v *taskWatcherAndNotify) Callback(c chan (<-chan zk.Event)) {

	for {
		ech := <-c
		event := <-ech

		if deleteType!=event.Type.String() && createType!= event.Type.String() {
			value,err := basic.GetZkNodeValue(event.Path)
			if err !=nil {
				errStr := fmt.Sprintf("taskName[%s] zkNode[%s] getValue err [%s]",v.task.TaskName,event.Path,err)
				log.Error(errStr)
				return
			}
			scanConfig(event.Path,value,v.task)
		}
		//事件回调以后，重新注册任务
		go v.Watcher(c)
	}
}

/**
	对某个节点进行一次Watcher，只生效一次
 */
func (v *taskWatcherAndNotify) Watcher(c chan (<-chan zk.Event)){
	_,_,event, errs := basic.GetZkClient().ExistsW(v.path)
	if errs != nil {
		errStr := fmt.Sprintf("zk ExistsW err ,path :[%s] err: [%s]",v.path,errs)
		log.Error(errStr)
		return
	}
	c <-event
}
/**
	注册监听和回调
 */
func (v *taskWatcherAndNotify) StartWatchAndNotify(){
	go v.Callback(v.channel)
	go v.Watcher(v.channel)
}


